import { defineStore } from 'pinia'

export const useSaveFilePathStore = defineStore('file-path', {
  state: ():{saveFilePath: string[]} => ({
    saveFilePath: null
  }),
  actions: {
    setSaveFilePath(value: string): void {
      if (!this.saveFilePath?.includes(value)) {
        try {
          // 1. 在内存中先进行修改
          this.saveFilePath?.push(value)
          // 2. 尝试将新状态写入 localStorage
          localStorage.setItem('gitDirectories', JSON.stringify(this.saveFilePath))
          // 3. 如果写入成功，则提交内存中的修改（这里已经是成功的状态）
          console.log('Successfully added and saved:', value)
        } catch (error) {
          // 如果写入失败，则回滚内存状态
          if (this.saveFilePath) {
            this.saveFilePath.pop() // 回滚添加的操作
          }
          console.error('Failed to save to localStorage:', error)
        }
      }else {
        console.log('Already exists:', value)
      }
    },
    getSaveFilePath(): string[] {
      if (this.saveFilePath === null) {
        const value = localStorage.getItem('gitDirectories')
        this.saveFilePath = JSON.parse(value)
      }
      return this.saveFilePath
    }
  }
})
